/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;

namespace DNNContentBuilder
{
    /// <summary>
	///		Summary description for epContentViewerView.
	/// </summary>
	public class ContentViewerView : PortalModuleBase, IActionable, ISearchable
	{
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/ContentViewerView";
/*
		private const string IGNORE_USER_ROLES = "<IGNORE_ROLES>";
*/

		protected PlaceHolder templateHolder;
		protected ContentViewerSettingsController cvsController = new ContentViewerSettingsController();
		protected ContentViewerSettingsInfo cvsInfo = new ContentViewerSettingsInfo();
		protected TemplateDefinitionController tdController = new TemplateDefinitionController();
		protected TemplateDefinitionInfo tdInfo = new TemplateDefinitionInfo();
		protected System.Web.UI.UserControl myTemplate = null;
		
		public string UserRoles {
			get { 
				 string userRoles = "";
				 
				 try {
					 for (int loop = 0; loop < this.UserInfo.Roles.Length - 1 ; loop++) {
					 	userRoles += this.UserInfo.Roles[loop] + ",";
				 	 }
				 }
				 
			 	 catch (Exception) {
				 	userRoles = "";				 		
			 	 }
				 
				 return  userRoles.Length > 0 ? userRoles.Substring(0,userRoles.Length - 1)	: "";
			}
		}

		private void Page_Load(object sender, EventArgs e)
		{
			// Put user code to initialize the page here

			Literal literal = new Literal();

			try 
			{
				myTemplate = (System.Web.UI.UserControl)Page.LoadControl(@"DesktopModules\DNNContentBuilder\Templates\$Live\" + this.ModuleId.ToString() + ".ascx");
				
				templateHolder.Controls.Add(myTemplate);
			}
			catch (Exception err)
			{
				try {
					if (File.Exists(HttpContext.Current.Server.MapPath(@"~\DesktopModules\DNNContentBuilder\Templates\$Live\" + this.ModuleId.ToString() + ".ascx"))) {
					    literal.Text = err.Message;

					    templateHolder.Controls.Add(literal);
					} else {
						myTemplate = (System.Web.UI.UserControl)Page.LoadControl(@"DesktopModules\DNNContentBuilder\Templates\$Live\Dummy.ascx");
				
						templateHolder.Controls.Add(myTemplate);
					}
				}
				catch (Exception error) {
                    Commons.LogError(error, "DNN Content Builder: ContentViewerView");
					// TODO: to log the error
				}
			}
		}

		#region Properties
		public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions  
		{
			get 
			{
				DotNetNuke.Entities.Modules.Actions.ModuleActionCollection actions = new DotNetNuke.Entities.Modules.Actions.ModuleActionCollection();

				actions.Add(GetNextActionID(), Commons.GetLocalizedString("label_EditTemplate", resource), "","","", this.EditUrl("Template Settings","","TemplateSettingsControl"), "", false, DotNetNuke.Security.SecurityAccessLevel.Admin, true, false);

				return actions;
			}
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.Unload +=new EventHandler(ContentViewerView_Unload);

		}
		#endregion

		private void ContentViewerView_Unload(object sender, EventArgs e)
		{
			if (myTemplate != null) 
			{
				myTemplate.Dispose();
			}
		}
		#region ISearchable Members

		public DotNetNuke.Services.Search.SearchItemInfoCollection GetSearchItems(ModuleInfo ModInfo)
		{
			// search support needs some improvement since metadata has just title, no description. 

			DotNetNuke.Services.Search.SearchItemInfoCollection searchItemInfoCollection = new DotNetNuke.Services.Search.SearchItemInfoCollection();

			MetaDataController metaDataController = new MetaDataController();

			//TODO: to confirm that unauthenticated returns "unregistered";
			string userRoles = "";
			
			if (this.UserInfo != null) {
				userRoles = this.UserInfo.Roles.ToString().Replace(" ",", ");
			}
			
			TemplateDefinitionController tdController = new TemplateDefinitionController();
			TemplateDefinitionInfo tdInfo = tdController.GetByModuleId(this.ModuleId);
			
			if (tdInfo == null) {
				return null;
			}
			
			ArrayList metadata = metaDataController.GetMoreRecentApprovedContent(this.PortalId, tdInfo.FormDefinitionId, userRoles);

			foreach(MetaDataInfo metaDataInfo in metadata) 
			{
				DotNetNuke.Services.Search.SearchItemInfo searchItemInfo = new DotNetNuke.Services.Search.SearchItemInfo(metaDataInfo.Title, "", metaDataInfo.UserID, metaDataInfo.PublishDate, this.ModuleId, metaDataInfo.MetaDataId.ToString(), "", "PKValue=" + metaDataInfo.PKValue);

				searchItemInfoCollection.Add(searchItemInfo);
			}

            return searchItemInfoCollection;
		}

		#endregion
	}
}

